import { _decorator, Color, color, EventKeyboard, Input, input, RenderTexture, sys, tween, Vec2, view } from 'cc';
import * as fgui from "fairygui-cc";
import AbstractUIWindow from '../../window/AbstractUIWindow';
import UICore from '../../../../Core/Res/UICore';
import { ViewManager } from '../../base/ViewManager';
import SpineLoader from '../../../../Core/Res/SpineLoader';
// import { ExternalGLoader } from '../../../../Core/Res/ExternalGLoader';
import WindowManager from '../../window/WindowManager';
import ModuleWindow from '../../window/ModuleWindow';
import WindowObject from '../../window/WindowObject';
import EventMgr from '../../../../Core/Event/EventMgr';
import TimerMgr from '../../../../Core/Timer/TimerMgr';
import ArrayUtil from '../../../../Core/Utils/ArrayUtil';
import SdkTool from '../../../../Core/Sdk/SdkTool';
import { EnumplatFrom } from '../../../../Core/Sdk/EnumplatFrom';
import CoreUtil from '../../base/CoreUtil';
import AudioManager from '../../../../Core/Audio/AudioManager';
import { Grid } from '../../view/game/Grid';
import { ModelGame } from '../../model/ModelGame';
export class MainView extends AbstractUIWindow {
    private __prevent: boolean = false;//是否正在消除
    private _gridList: Grid[][];
    private _gridArray: Grid[] = [];
    private _gridTempArray: Grid[] = [];
    private _startPos: Vec2;
    private ceshi: fgui.GButton;
    private txt_coin: fgui.GTextField;
    private menu: fgui.GButton;
    protected getResList(): Array<string> {
        return [`Main`];
    }
    protected onInit(): void {
        UICore.registerExtension(`Main`, `Grid`, Grid);
        this._view = UICore.createObject("Main", "MainView").asCom;
        this.notClose = true;
    }
    protected onShow(): void {
        EventMgr.on(`GridClick`, this.clickGrid, this);
        EventMgr.on(`upgrade`, () => {
            this.txt_coin.text = `${ModelGame.coin}`;
        }, this);
        this._startPos = new Vec2((this.view.width - (ModelGame.rows * ModelGame.gridwidth)) * 0.5, (this.view.height - (ModelGame.columns * ModelGame.gridheight)) * 0.5);
        this.createUI();
        this.ceshi.onClick(() => {
            this.shuffleTheCards();
        });
        this.txt_coin.text = ModelGame.coin + ``;
        this.menu.onClick(() => {
            ModuleWindow.ins.openWindow(WindowObject.ins.UpgradeWindow);
        }, this);
    }
    private set coin(val: number) {
        ModelGame.coin = val;
        this.txt_coin.text = `${ModelGame.coin}`;
    }
    private createUI(): void {
        this._gridList = [];
        for (let i = 0; i < ModelGame.rows; i++) {
            if (!this._gridList[i]) {
                this._gridList[i] = [];
            }
            for (let j = 0; j < ModelGame.columns; j++) {
                const grid = this.createGrid();
                this._gridList[i][j] = grid;
                grid.setData(i, j, false);
                grid.active = true;
                grid.setPosition(this._startPos.x + (i * ModelGame.gridwidth), this._startPos.y);
                grid.tweenToPos(grid.x, this._startPos.y + (j * ModelGame.gridheight));
            }
        }
        console.log(this._gridList);
    }
    private clickGrid(grid: Grid): void {
        if (!grid.active) {
            return;
        }
        if (this.__prevent) {
            return;
        }
        // console.log(`点击了网格:${grid.name}`, grid.x, grid.y);
        // grid.tweenToScale(0, () => {
        //     this.deletdGrid(grid);
        //     this.checkCreateNewGrid();
        // }, 0.2);
        this._gridTempArray = [];
        this.BFS(grid, grid.gridPos.x, grid.gridPos.y);
        if (this._gridTempArray.length > 2) {
            let coin: number = 0;
            let _score = 0;
            for (let i of this._gridTempArray) {
                if (i.state == 1) {
                    _score = i.score * this._gridTempArray.length * 2;
                } else {
                    _score = i.score * this._gridTempArray.length;
                }
                coin += _score;
            }
            ViewManager.ins.showCoin(coin, this.view, new Vec2(grid.x, grid.y), new Vec2(this.txt_coin.x, this.txt_coin.y), () => {
                this.coin = coin;
            });
            this.__prevent = true;
            for (let i = 0; i < this._gridTempArray.length; i++) {
                const grid = this._gridTempArray[i];
                grid.tweenToScale(0, () => {
                    this.deletdGrid(grid);
                }, 0.2);
            }
            TimerMgr.ins.add(300, 1, this.check, this);
        } else {
            // console.log(`匹配数量不足3个`, this._gridTempArray.length);
        }
    }
    private BFS(_grid: Grid, x: number, y: number): void {
        if (x < 0 || y < 0 || x > ModelGame.rows - 1 || y > ModelGame.columns - 1) { return }
        // console.log(`开始查询：${x},${y} `);
        const grid = this._gridList[x][y];
        if (!grid) {
            return;
        }
        if (!grid.active) {
            return;
        }
        if (grid.u_icon != _grid.u_icon) {
            return;
        }
        if (this._gridTempArray.indexOf(grid) != -1) {
            return;
        }
        this._gridTempArray.push(grid);
        this.chenckGrid(grid, x, y);
    }
    private chenckGrid(grid, x, y): void {
        this.BFS(grid, x + 1, y);
        this.BFS(grid, x, y + 1);
        this.BFS(grid, x - 1, y);
        this.BFS(grid, x, y - 1);
    }
    private check(): void {
        this._gridTempArray = [];
        this.checkCreateNewGrid();
        if (this.checkFinsh()) {
            ViewManager.ins.showtips(`界面没有可以消除的格子`);
            TimerMgr.ins.add(500, 1, this.shuffleTheCards, this);
        }
        this.__prevent = false;
    }
    private shuffleTheCards(): void {
        for (let i = 0; i < ModelGame.rows; i++) {
            for (let j = ModelGame.columns - 1; j >= 0; j--) {
                const grid = this._gridList[i][j];
                if (!grid) {
                    continue;
                }
                if (grid.state != 0) {
                    continue;
                }
                grid.tweenToPos2(this.view.width * 0.5, this.view.height * 0.5);
            }
        }
    }
    private checkCreateNewGrid(): void {
        for (let i = ModelGame.rows - 1; i >= 0; i--) {
            for (let j = ModelGame.columns - 1; j >= 0; j--) {
                if (this._gridList[i][j] == null) {
                    for (let y = j - 1; y >= -1; y--) {
                        // console.log(`找到格子：${i},${y} `);
                        if (y == -1) {
                            const grid = this.createGrid();
                            this._gridList[i][y] = null;
                            this._gridList[i][j] = grid;
                            grid.setData(i, j);
                            grid.active = true;
                            grid.setPosition(this._startPos.x + (i * ModelGame.gridwidth), this._startPos.y - ModelGame.gridheight);
                            grid.tweenToPos(grid.x, this._startPos.y + (j * ModelGame.gridheight), null, 0.2);
                            break;
                        }
                        if (this._gridList[i][y]) {
                            const grid = this._gridList[i][y];
                            this._gridList[i][y] = null;
                            this._gridList[i][j] = grid;
                            grid.changePos(i, j);
                            grid.active = true;
                            grid.tweenToPos(grid.x, this._startPos.y + (j * ModelGame.gridheight), null, 0.2);
                            break;
                        }
                    }
                }
            }
        }
    }

    private checkFinsh(): boolean {
        for (let i = 0; i < ModelGame.rows; i++) {
            for (let j = 0; j < ModelGame.columns; j++) {
                this._gridTempArray = [];
                this.BFS(this._gridList[i][j], i, j);
                if (this._gridTempArray.length > 2) {
                    return false;
                }
            }
        }
        return true;
    }
    /**
     * 创建网格对象
     * @returns 返回创建的网格对象
     */
    private createGrid(): Grid {
        if (this._gridArray.length > 0) {
            const grid = this._gridArray.pop();
            grid.u_icon = ModelGame.pieceValue;
            return grid;
        } else {
            const grid = UICore.createObject(`Main`, `Grid`).asCom as Grid;
            grid.u_icon = ModelGame.pieceValue;
            this.view.addChild(grid);
            return grid;
        }
    }
    /**
     * 删除网格并添加到网格数组中
     * @param grid 要删除的网格对象
     * @returns 返回布尔值，表示操作是否成功
     */
    private deletdGrid(grid: Grid): boolean {
        grid.name = ``;
        grid.active = false;
        grid.setScale(1, 1);
        grid.reset();
        this._gridList[grid.gridPos.x][grid.gridPos.y] = null;
        this._gridArray.push(grid);
        return true;
    }
}



